import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import '../model/chatMessageModel.dart';
import '../model/conversation.dart';
import 'websocketprovider.dart';
import '../utils/sputil.dart';

class ChatDetailProvider with ChangeNotifier {
  late Conversation conversation;
  ChatDetailProvider(conversation) {
    this.conversation = conversation;
  }

  var spu = SpUtil();

  String get username {
    return spu.get<String>("username") as String;
  }

  String get sessionId {
    if (username.compareTo(conversation.userId) > 0) {
      return "${username},${conversation.userId}";
    } else {
      return "${conversation.userId},${username}";
    }
  }

  String get toUserId {
    return conversation.userId;
  }

  bool toUserOnline = false;
  checkUserOnline(List<dynamic> peers){
    toUserOnline = peers.where((element) => element["id"] == toUserId).isNotEmpty;
    if(toUserOnline){
      print("${toUserId} 上线");
    }else
      {
        print("${toUserId} 离线");
      }


    notifyListeners();
  }

  String get newMsgId {
    var id = Uuid().v1();

    return id;
  }

  final List<ChatMessage> messages = <ChatMessage>[];

  ///发送聊天信息
  chat(String msg) async {
    dynamic data = {
      'session_id': sessionId,
      'to': toUserId,
      'from': username,
      'msg_id': newMsgId,
      'msg': msg,
      'msgtype': 'text'
    };

    await WebSocketProvider().chat(data);

    messages.add(ChatMessage(messageContent: msg, messageType: "sender"));

    notifyListeners();
  }

  ///接收到消息
  receive(dynamic data) {
    messages
        .add(ChatMessage(messageContent: data["msg"], messageType: "receiver"));

    notifyListeners();
  }
}
